package com.jiang.spring_security_singleboot.service.impl;

import com.jiang.spring_security_singleboot.domain.SysRole;
import com.jiang.spring_security_singleboot.domain.SysUser;
import com.jiang.spring_security_singleboot.mapper.UserMapper;
import com.jiang.spring_security_singleboot.service.IRoleService;
import com.jiang.spring_security_singleboot.service.IUserService;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @中软华腾软件系统有限公司,未经授权不得擅自传播
 * @类描述: 用户管理业务类
 * @类名称:UserService
 * @作者: 蒋正午
 * @编辑时间: 2021/4/27 9:15
 * @版本: 1.0
 */
@Service
public class UserServiceImpl implements IUserService {

    @Resource
    private UserMapper userMapper;
    // 引入加密器
    @Resource
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    @Resource
    private IRoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return userMapper.findUsersByUsername(username).get(0);
    }

    @Override
    public void save(SysUser user) {
        user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
        userMapper.save(user);
    }

    @Override
    public List<SysUser> findAll() {
        return userMapper.findAll();
    }

    @Override
    public Map<String, Object> toAddRolePage(Integer id) {
        List<SysRole> allRoles = roleService.findAll();
        List<Integer> myRoles = userMapper.findRolesByUid(id);
        Map<String, Object> map = new HashMap<>();
        map.put("allRoles", allRoles);
        map.put("myRoles", myRoles);
        return map;
    }

    @Override
    public void addRoleToUser(Integer userId, Integer[] ids) {
        userMapper.removeRoles(userId);
        for (Integer rid : ids) {
            userMapper.addRoles(userId, rid);
        }
    }

}
